package com.scott.itcast.countdown;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 倒计时计数器
 */
public class CountdownLatchTest {

	public static void main(String[] args) {
		
		ExecutorService threadPool = Executors.newCachedThreadPool();
		
		//主裁判  主裁判吹1声就开始跑
		final CountDownLatch cdOrder = new CountDownLatch(1);
		
		//运动员  3个运动员跑完了才能公布比赛结果
		final CountDownLatch cdAnswer = new CountDownLatch(3);	
		
		//三个子线程
		for(int i=0;i<3;i++){
			Runnable runnable = new Runnable(){
					public void run(){
					try {
						System.out.println("运动员线程[" + Thread.currentThread().getName() + "]走到跑道上并等待裁判命令准备开始跑...");	
						//等cdOrder归0
						cdOrder.await();
						System.out.println("运动员线程[" + Thread.currentThread().getName() + "]在100米赛跑中...");								
						Thread.sleep((long)(Math.random()*20000));	
						System.out.println("运动员线程[" + Thread.currentThread().getName() + "]已经跑完100米 并报告比赛成绩给主裁判...");
						//把cdAnswer身上的计数减1
						cdAnswer.countDown();						
					} catch (Exception e) {
						e.printStackTrace();
					}				
				}
			};
			threadPool.execute(runnable);
		}	
		
		//主线程
		try {
			Thread.sleep((long)(Math.random()*10000));
		
			System.out.println("主裁判线程[" + Thread.currentThread().getName() + "]发布开始赛跑命令...");
			
			//把cdOrder身上的计数减1
			cdOrder.countDown();
			
			
			//等cdAnswer
			cdAnswer.await();
			System.out.println("主裁判线程[" + Thread.currentThread().getName() + "]已收到所有比赛结果并公布比赛成绩....");	
		} catch (Exception e) {
			e.printStackTrace();
		}				
		threadPool.shutdown();

	}
}
